import axios from "axios";
import getShortcutByName from "./getShortcutByName";
import {accessToken, instanceUrl } from "./constants";

const updateShortcutViewstate = async (name: string, viewstate: string) => {
  const data = await getShortcutByName(name);
  if (!data.shortcut) {
    return;
  }
  const shortcut = data.shortcut;
  const id = shortcut.id;
  const existingViewstates = shortcut.comments.trim().split("\n\n");
  // 从已保存的viewstates中过滤掉输入的这个viewstate，后续再追加上去
  const viewstatesWithoutInput = existingViewstates.filter(item => {
    const [itemHighlightId] = item.split(";;").slice(0);
    const [inputHighlightId] = viewstate.split(";;").slice(0);
    return itemHighlightId !== inputHighlightId;
  });
  viewstatesWithoutInput.push(viewstate);

  const normalizedUrl = instanceUrl.replace(/\/+$/, "");
  const body = JSON.stringify({
    "id": id,
    "comments": viewstatesWithoutInput.join("\n\n"),
  });
  const resp = await axios.put(`${normalizedUrl}/api/v1/shortcuts/${id}?updateMask=comments`, body, {
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
  });
  if (resp.status !== 200) {
    throw Error(`updateShortcutViewstate error: ${resp.statusText}, status code ${resp.status}`);
  }
  return resp.data;
}

export default updateShortcutViewstate;
